package cn.meye11.crm.service;

import cn.meye11.crm.common.DateUtils;
import cn.meye11.crm.common.RestResponse;
import cn.meye11.crm.common.StringUtils;
import cn.meye11.crm.domain.entity.ConsumptionRecordsEntity;
import cn.meye11.crm.domain.entity.MemberEntity;
import cn.meye11.crm.domain.model.ConsumptionRecords;
import cn.meye11.crm.domain.query.ConsumptionRecordsQuery;
import cn.meye11.crm.mapper.ConsumptionRecordsMapper;
import cn.meye11.crm.mapper.MemberMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消费记录表(ConsumptionRecords)表服务实现类
 * 默认CRUD操作
 *
 * @author makejava
 * @since 2023-11-18 19:20:43
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ConsumptionRecordsService {

    private final ConsumptionRecordsMapper consumptionRecordsMapper;
    private final ObjectMapper objectMapper;
    private final MemberMapper memberMapper;
    // 代码写到此区域


    /************************************* 请在上方编写新代码 **************************************/
    // 此区域为自动生成的通用代码 尽量不直接修改
    @Transactional(rollbackFor = Exception.class)
    public Long save(ConsumptionRecords model) {
        if (StringUtils.isNotBlank(model.getOperators())) {
            model.setCreatedBy(model.getOperators());
            model.setModifiedBy(model.getOperators());
        } else {
            model.setCreatedBy("Genkai");
            model.setModifiedBy("Genkai");
        }
        if (StringUtils.isBlank(model.getCreatedBy())) {
            throw new RuntimeException("创建人不能为空");
        }
        if (model.getId() != null) {
            throw new RuntimeException("主键id不可自定义");
        }
        if (model.getVersion() != null) {
            throw new RuntimeException("数据版本号不可自定义");
        }
        if (model.getTime() != null) {
            throw new RuntimeException("数据创建时间不可自定义");
        }
        if (model.getLast() != null) {
            throw new RuntimeException("数据修改时间不可自定义");
        }
        if (Objects.isNull(model.getAmount())) {
            throw new RuntimeException("消费金额不能为空");
        }

        //记录本次扣减的充值金额和赠送金额
        double rechargeAmount = 0d;
        double giftAmount = 0d;
        // 如果memberID传入的是 0 则代表是散客消费， 不走余额校验和会员信息校验
        if (!ObjectUtils.isEmpty(model.getMemberId()) && model.getMemberId() != 0) {
            /* 重要： 消费完成后，需要更新会员表中的账户充值余额 和账户赠送余额信息*/
            MemberEntity member = memberMapper.selectByPrimaryKey(model.getMemberId());
            if (ObjectUtils.isEmpty(member)) {
                throw new RuntimeException("会员信息不存在，无法进行消费!");
            }

            // 判断账户余额是否足够消费
            if (Objects.isNull(member.getRechargeBalance()) && Objects.isNull(member.getGiftBalance())) {
                throw new RuntimeException("账户余额不足，无法进行消费!\n 当前账户余额为：【0】元");
            }
            double balance = (member.getRechargeBalance() == null ? 0d : member.getRechargeBalance()) +
                    (member.getGiftBalance() == null ? 0d : member.getGiftBalance());
            if (balance < model.getAmount()) {
                throw new RuntimeException("账户余额不足，无法进行消费!\n 当前账户余额为：【" + balance + "】元");
            }

            // 判断充值金额是否大于本次消费金额， 如果是，则只扣减充值金额； 否则扣减充值金额和赠送金额
            if (member.getRechargeBalance() > 0 && member.getRechargeBalance() > model.getAmount()) {
                member.setRechargeBalance(member.getRechargeBalance() - model.getAmount());
                rechargeAmount = model.getAmount();
            } else {
                double difference = model.getAmount() - member.getRechargeBalance();
                rechargeAmount = member.getRechargeBalance();
                giftAmount = difference;

                // 充值金额扣减为0
                member.setRechargeBalance(0d);
                member.setGiftBalance(member.getGiftBalance() - difference);
            }
            member.setId(model.getMemberId());
            memberMapper.updateByPrimaryKeySelective(member);
        } else {
            rechargeAmount = model.getAmount();
        }
        // 插入消费记录
        ConsumptionRecordsEntity entity = new ConsumptionRecordsEntity(model);
        entity.setAmount(rechargeAmount);
        entity.setGiftAmount(giftAmount);
        entity.setTime(DateUtils.toLocalDateTime(new Date()));
        entity.setLast(DateUtils.toLocalDateTime(new Date()));
        entity.setConsumptionTime(DateUtils.toLocalDateTime(new Date()));
        consumptionRecordsMapper.insertSelective(entity);

        return entity.getId();
    }

    public void remove(Long id) {
        if (id == null) {
            throw new RuntimeException("ID不能为空");
        }
        ConsumptionRecordsEntity entity = consumptionRecordsMapper.selectByPrimaryKey(id);
        if (entity == null) {
            throw new RuntimeException("ID:" + id + "不存在");
        }
        consumptionRecordsMapper.deleteByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ConsumptionRecords model) {

        if (model.getId() == null) {
            throw new RuntimeException("ID不能为空");
        }

        if (StringUtils.isBlank(model.getModifiedBy())) {
            throw new RuntimeException("修改人不能为空");
        }

        ConsumptionRecordsEntity entity = consumptionRecordsMapper.selectByPrimaryKey(model.getId());
        if (entity == null) {
            throw new RuntimeException("ID:" + model.getId() + "不存在");
        }

        ConsumptionRecordsEntity save = new ConsumptionRecordsEntity(model);
        save.setLast(LocalDateTime.now());
        save.setTime(entity.getTime());
        consumptionRecordsMapper.updateByPrimaryKey(save);
    }

    public ConsumptionRecords get(Long id) {
        ConsumptionRecordsEntity entity = consumptionRecordsMapper.selectByPrimaryKey(id);
        return entity == null ? null : new ConsumptionRecords(entity);
    }

    public Long count(ConsumptionRecordsQuery query) {
        return consumptionRecordsMapper.count(query);
    }

    public RestResponse<List<ConsumptionRecords>> list(ConsumptionRecordsQuery query) {
        // 单次查不得大于32767条数据，否则需要分页
        query.setLimit((int) Short.MAX_VALUE);
        return page(query);
    }

    public RestResponse<List<ConsumptionRecords>> page(ConsumptionRecordsQuery query) {
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<ConsumptionRecordsEntity> list = consumptionRecordsMapper.list(query);
        PageInfo<ConsumptionRecordsEntity> count = new PageInfo<>(list);
        List<ConsumptionRecords> collect = list.stream().map(ConsumptionRecords::new).collect(Collectors.toList());
        return RestResponse.success(count.getTotal(), collect);
    }
}
